<?php namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Predis\Client;

class WxMarketingService
{
    public function addAction($sociaType, $setId, $url, $clickId, $params = [], $actionType = 'COMPLETE_ORDER')
    {
        /**
         * @var Client $redis
         */
        $redis = Redis::connection('legacy');
        $appId = config("social.$sociaType.appid");
        if (!$appId) return;
        $access = $redis->get("wechat_access_token$appId");
        if (!$access)  return;
        $client = new \GuzzleHttp\Client();
        $json = [
            'actions' => [
                [
                    'user_action_set_id' => $setId,
                    'url' => $url,
                    'action_time' => Carbon::now()->getTimestamp(),
                    'action_type' => $actionType,
                    'trace' => [
                        'click_id' => $clickId,
                    ],
                    'action_param' => $params
                ]
            ],
        ];
        $response = $client->post("https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token=$access", [
            'json' => $json,
        ]);
        Log::info('[WxMarketingAction] Data: ' . json_encode($json) . ", Response:" . $response->getBody());

    }
}
